package cn.groupmarket.domain.trade.service.filter;

import cn.groupmarket.domain.trade.adapter.repository.ITradeOrderRepository;
import cn.groupmarket.domain.trade.model.entity.GroupBuyActivityEntity;
import cn.groupmarket.domain.trade.model.entity.TradeRuleCommandEntity;
import cn.groupmarket.domain.trade.model.entity.TradeRuleFilterBackEntity;
import cn.groupmarket.domain.trade.service.ITradeOrderService;
import cn.groupmarket.domain.trade.service.factory.TradeRuleFilterFactory;
import cn.groupmarket.types.design.framework.link.model1.ILogicLink;
import cn.groupmarket.types.design.framework.link.model2.handler.ILogicHandler;
import cn.groupmarket.types.enums.ActivityStatusEnumVO;
import cn.groupmarket.types.enums.ResponseCode;
import cn.groupmarket.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class ActivityUsabilityRuleFilter implements ILogicHandler<TradeRuleCommandEntity, TradeRuleFilterFactory.DynamicContext, TradeRuleFilterBackEntity> {
    @Resource
    private ITradeOrderRepository tradeOrderRepository;

    @Override
    public TradeRuleFilterBackEntity apply(TradeRuleCommandEntity requestParameter, TradeRuleFilterFactory.DynamicContext dynamicContext) throws Exception {

        log.info("交易规则过滤-活动可用性校验{} activityId:{}",requestParameter.getUserId(),requestParameter.getActivityId());

        GroupBuyActivityEntity groupBuyActivity = tradeOrderRepository.queryGroupBuyActivityByActivityId(requestParameter.getActivityId());
        if(!groupBuyActivity.getStatus().equals(ActivityStatusEnumVO.EFFECTIVE)){
            throw new AppException(ResponseCode.E0101);
        }
        Date currentDate = new Date();
        if(currentDate.before(groupBuyActivity.getStartTime())||currentDate.after(groupBuyActivity.getEndTime())){
            throw new AppException(ResponseCode.E0102);
        }
        dynamicContext.setGroupBuyActivityEntity(groupBuyActivity);
        return next(requestParameter, dynamicContext);
    }
}
